package com.yckj.activechicken.business.system.controller;

import com.yckj.activechicken.business.system.model.SysUser;
import com.yckj.activechicken.business.system.service.ISysPostService;
import com.yckj.activechicken.business.system.service.ISysRoleService;
import com.yckj.activechicken.business.system.service.ISysUserService;
import com.yckj.activechicken.common.constant.UserConstants;
import com.yckj.activechicken.common.utils.StringUtils;
import com.yckj.activechicken.common.utils.poi.ExcelUtil;
import com.yckj.activechicken.common.utils.security.SecurityUtils;
import com.yckj.activechicken.common.utils.spring.ServletUtils;
import com.yckj.activechicken.framework.security.model.LoginUser;
import com.yckj.activechicken.framework.security.service.TokenService;
import com.yckj.activechicken.framework.web.controller.BaseController;
import com.yckj.activechicken.framework.web.domain.AjaxResult;
import com.yckj.activechicken.framework.web.page.TableDataInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * Title:com.yckj.activechicken.business.controller
 * </p>
 * <p/>
 * <p>
 * Description: 描述【用户信息管理控制器】
 * </p>
 * <p/>
 * <p>
 * Copyright: Copyright (c) 2019
 * </p>
 * <p/>
 * <p>
 * Company: 英才汇硕信息技术有限公司
 * </p>
 *
 * @author zhoujy
 * @version 1.0
 * @created 2020/5/18 15:27
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private TokenService tokenService;

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    /**
     * 多条件分页获取用户信息列表
     * @param user
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/listCond")
    public TableDataInfo listCond(SysUser user) {
        Map<String,Object> outMap = userService.selectUserByCond(user);

        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setCode(200);
        tableDataInfo.setMsg(0);
        tableDataInfo.setTotal((int)outMap.get("total"));
        tableDataInfo.setRows((List<SysUser>)outMap.get("list"));
        return tableDataInfo;
    }

    /**
     * 用户名模糊查询用户及员工信息，分页
     * @param username
     * @return
     */
    @GetMapping("/queryUserEmpByUserName")
    public TableDataInfo queryUserEmpByUserName(String username) {
        startPage();
        List<SysUser> list = userService.queryUserEmpByUserName(username);
        return getDataTable(list);
    }


    /**
     * 用户数据导出，文档生成
     * @param user
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @GetMapping("/export")
    public AjaxResult export(SysUser user) {
        Map<String,Object> outMap = userService.selectUserByCond(user);
        List<SysUser> list = (List<SysUser>)outMap.get("list");
        list = userService.queryEmpToUserList(list);
        ExcelUtil<SysUser> util = new ExcelUtil<>(SysUser.class);
        return util.exportExcel(list, "用户数据");
    }

    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    /**
     * 导入模板操作
     * @return
     */
    @GetMapping("/importTemplate")
    public AjaxResult importTemplate() {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/getInfo", "/getInfo/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Integer userId) {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("roles", roleService.selectRoleAll());
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            ajax.put(AjaxResult.DATA_TAG, userService.selectUserById(userId));
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，用户名称已存在");
        }

        String username = SecurityUtils.getUsername();
        Date newDate = new Date();
        user.setCreateBy(username);
        user.setCreateTime(newDate);
        user.setUpdateBy(username);
        user.setUpdateTime(newDate);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @PostMapping("/edit")
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        user.setUpdateTime(new Date());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @GetMapping("/remove/{userIds}")
    public AjaxResult remove(@PathVariable Integer[] userIds) {
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        user.setUpdateTime(new Date());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        user.setUpdateTime(new Date());
        return toAjax(userService.updateUserStatus(user));
    }
}